<?php

class CisAdminController extends AppController
{
    # Controller Name to be used
    var $name = 'CisAdmin';

    # Models to be used
    var $uses = array(
        'CisUser'
    );

    # set the layout to use
    var $layout = 'cis_layout';

    function __validateLoginStatus()
    {
        if ($this->params['action'] != 'login' && $this->params['action'] != 'logout') {
            if ($this->Session->check('loginData') == false) {
                $this->redirect(array('action' => 'login?ref=' . $this->params['action']));
            } else {
                $auth_user = $this->Session->read('loginData');
                //check if the user has not done multiple login
                $db_login_session = $this->getLoginSession($auth_user['id']);
                $login_session = $auth_user['login_session'];
                if ($db_login_session != $login_session) {
                    $this->Session->setFlash('Your session has expired!');
                    $this->redirect(array('action' => 'logout'));
                }
                //authorize the user, if the user is not authorized to view this page then redirect them to their session
                //$auth_user = $this->Session->read('loginData');
                if ($auth_user['user_type'] != 'cis_user') {
                    if ($auth_user['user_type'] == 'student_user') {
                        $this->redirect(array('controller' => 'Student', 'action' => 'index'));
                    } elseif ($auth_user['user_type'] == 'bank_user') {
                        $this->redirect(array('controller' => 'Bank', 'action' => 'index'));
                    } elseif ($auth_user['user_type'] == 'staff_user') {
                        $this->redirect(array('controller' => 'Staff', 'action' => 'index'));
                    }
                    else {
                        $this->redirect(array('action' => 'logout'));
                    }
                } else { // For Admin Staff only
                    $user_level = $auth_user['user_level'];
                    if ($user_level != 'Admin') {
                        $this->redirect(array('controller' => 'Cis', 'action' => 'index'));
                    }
                }
            }
        }
    }

    private function getLoginSession($user_id)
    {
        $data = $this->CisUser->find('first', array(
            'conditions' => array('id' => $user_id),
            'recursive' => -1
        ));
        return $data['CisUser']['login_session'];
    }

    function  beforeFilter()
    {
        parent::beforeFilter();
        $this->__validateLoginStatus();
    }

    public function logout()
    {
        $this->redirect(array('controller' => 'staff', 'action' => 'logout'));
    }


    # Controller actions
    /**
     * @name index
     * @param void
     * @return Array of data.
     * @access public
     */
    function index()
    {
        $this->redirect(array('action' => 'cis_users'));
    }


    function cis_users($type = 'get')
    {

        if ($this->request->is('ajax')) {
            $this->autoRender = false;
            $this->autoLayout = false;
            $auth_user = $this->Session->read('loginData');
            switch ($type) {
                case 'get' :
                    $_POST = $this->CisUser->sanitize($_POST);
                    /**  Get posted data */
                    $page = isset($_POST['page']) ? $_POST['page'] : 1;
                    /** The current page */
                    $sortname = isset($_POST['sortname']) ? $_POST['sortname'] : 'id';
                    /** Sort column */
                    $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc';
                    /** Sort order */
                    $qtype = isset($_POST['qtype']) ? $_POST['qtype'] : '';
                    /** Search column */
                    $search_query = isset($_POST['query']) ? $_POST['query'] : '';
                    /** Search string */
                    $rp = isset($_POST['rp']) ? $_POST['rp'] : 10;
                    $limit = $rp;
                    $start = ($page - 1) * $rp;

                    //get users id for this company only

                    $condition_array = array(
                        'CisUser.deleted' => 'n'
                    );

                    if (!empty($search_query)) {
                        if ($qtype == 'username') {
                            /*$condition_array = array(
                                'User.username' => $search_query,
                                'User.deleted' => 'n'
                            );*/
                        } else {
                            /* $condition_array = array(
                                 "User.$qtype LIKE" => $search_query . '%',
                                 'User.deleted' => 'n'
                             );*/
                        }
                    }

                    $data_table = $this->CisUser->find('all', array('conditions' => $condition_array, 'order' => "CisUser.$sortname $sortorder", 'limit' => $start . ',' . $limit, 'recursive' => -1));
                    $data_table_count = $this->CisUser->find('count', array('conditions' => $condition_array, 'recursive' => -1));

                    $total_records = $data_table_count;

                    if ($data_table) {
                        $return_arr = array();
                        foreach ($data_table as $obj) {
                            $return_arr[] = array(
                                'id' => $obj['CisUser']['id'],
                                'cell' => array(
                                    $obj['CisUser']['id'],
                                    $obj['CisUser']['fname'],
                                    $obj['CisUser']['mname'],
                                    $obj['CisUser']['lname'],
                                    $obj['CisUser']['username'],
                                    $obj['CisUser']['user_level'],
                                )
                            );
                        }
                        return json_encode(array('success' => true, 'total' => $total_records, 'page' => $page, 'rows' => $return_arr));
                    } else {
                        return json_encode(array('success' => false, 'total' => $total_records, 'page' => $page, 'rows' => array()));
                    }
                    break;

                case 'save' :
                    if ($_POST['id'] == 0) {
                        //check if username does not exist for in this company
                        $username = $_POST['username'];
                        $res = $this->_validateUsername($username);
                        if ($res) {
                            return json_encode(array('success' => 1, 'msg' => 'Username already exist.'));
                        }
                    }
                    $data = array('CisUser' => $_POST);
                    $pass = '';
                    if ($_POST['id'] == 0) {
                        $pass = $this->randomPassString(8);
                        $data['CisUser']['password'] = md5($pass);
                        $data['CisUser']['user_type'] = 'cis_user';
                    }

                    if ($_POST['id'] > 0) {
                        $data['CisUser']['modified_by'] = $auth_user['id'];
                    } else {
                        $data['CisUser']['created_by'] = $auth_user['id'];
                    }

                    if ($this->CisUser->save($data['CisUser'])) {
                        if ($_POST['id'] > 0) {
                            return json_encode(array('code' => 0, 'msg' => 'Data Saved'));
                        } else { //If new pass back extra data if needed.
                            return json_encode(array('code' => 0, 'msg' => 'Data Saved!  The default password is ' . $pass, 'id' => $this->CisUser->id));
                        }
                    } else {
                        echo json_encode(array('code' => 1, 'msg' => 'Some errors occurred.'));
                    }
                    break;

                case 'reset_password':
                    $data = array(
                        'id' => $_POST['id'],
                        'password' => md5(trim($_POST['password']))
                    );
                    if ($this->CisUser->save($data)) {
                        return json_encode(array('code' => 0, 'msg' => 'Password has been reset.'));
                    } else {
                        echo json_encode(array('code' => 1, 'msg' => 'Password could not be reset.'));
                    }

                    break;

                case 'delete':
                    $ids = $_POST['ids'];
                    $modObj = ClassRegistry::init('CisUser');
                    $result = $modObj->updateAll(
                        array('CisUser.deleted' => "'y'"),
                        array('CisUser.id' => $ids)
                    );
                    if ($result) {
                        echo json_encode(array('code' => 0, 'msg' => 'Data Deleted!'));
                    } else {
                        echo json_encode(array('code' => 1, 'msg' => 'Data cannot be deleted'));
                    }
                    break;
            }
        }

        $user_levels = array(
            array('id' => 'Admin', 'name' => 'Admin'),
            array('id' => 'Normal', 'name' => 'Normal')
        );


        $this->set(compact('user_levels'));
    }


    function _validateUsername($username = null, $type = 'staff')
    {
        if ($type == 'staff') {
            $data = $this->CisUser->find('first', array(
                'conditions' => array('CisUser.username' => $username),
                'recursive' => -1
            ));
        } else {
            $data = $this->StudentUser->find('first', array(
                'conditions' => array('StudentUser.username' => $username),
                'recursive' => -1
            ));
        }

        if ($data) {
            return true;
        } else {
            return false;
        }
    }


    function randomPassString($length)
    {
        return $this->randomString($length);
    }


    function clean_fonnumber($send_no)
    {

        if (!$send_no) {
            return $send_no;
        }
        $cell = '';

        if (strpos($send_no, ',') !== false) {
            $fon_numbers = explode(',', $send_no);
        } elseif (strpos($send_no, '/') !== false) {
            $fon_numbers = explode('/', $send_no);
        } else {
            $fon_numbers = trim($send_no);
        }
        if (is_array($fon_numbers)) {
            $cell = $send_no;
            /*foreach($fon_numbers as $fon){
                $fon = preg_replace('/-/', '', $fon);
                //$fon = preg_replace('/+/', '', $fon);
                $fon = trim($fon);
                if(strlen($fon) < 9){//not a mobile number
                    $cell .=  $fon.'/';
                }
                else{
                    $country_code = substr($fon, 0, 3);
                    $cell .= $fon;
                    if($country_code != '233'){
                        $f= substr($fon_numbers, 0,1);
                        if($f == '0'){
                            $cell .= '233'.substr($fon, 1).'/';
                        }
                        else{
                            $cell .= '233'.$fon.'/';
                        }

                    }
                }


            }*/
        } else {
            $fon_numbers = preg_replace('/-/', '', $fon_numbers);
            //$fon_numbers = preg_replace('/+/', '', $fon_numbers);
            $fon_numbers = trim($fon_numbers);
            if (strlen($fon_numbers) < 9) { //not a mobile number
                return $fon_numbers;
            }
            $country_code = substr($fon_numbers, 0, 3);

            $cell = $fon_numbers;
            if ($country_code != '233') {
                $f = substr($fon_numbers, 0, 1);
                if ($f == '0') {
                    $cell = '233' . substr($fon_numbers, 1);
                } else {
                    $cell = '233' . $fon_numbers;
                }

            }
        }
        //remove the dash separator if any
        return $cell;


    }


}